package com.shimao.celnet.payment.service.impl;

import com.github.pagehelper.PageHelper;
import com.shimao.celnet.payment.form.SCodeNameForm;
import com.shimao.celnet.payment.mapper.SCodeNameMapper;
import com.shimao.celnet.payment.model.SCodeName;
import com.shimao.celnet.payment.service.SCodeNameService;
import com.shimao.celnet.payment.util.FinalUtil;
import com.shimao.celnet.payment.util.MyDateUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 参数管理
 * Created by ensure on 2017/12/3.
 */
@Service
public class SCodeNameServiceImpl extends BaseServiceImpl<SCodeName> implements SCodeNameService {
    protected Logger logger = Logger.getLogger(this.getClass());
    @Autowired(required = false)
    private SCodeNameMapper sCodeNameMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分页查询
     *
     * @param formBean
     * @param pageNum
     * @param length
     * @return
     */
    @Override
    public SCodeNameForm getByPage(SCodeNameForm formBean, int pageNum, int length) {
        logger.info("分页查询--开始");
        //分页查询
        Example example = new Example(SCodeName.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtil.isNotEmpty(formBean.getName())) {
            //参数名称
            criteria.andLike("name", "%" + formBean.getName() + "%");
        }

        if (StringUtil.isNotEmpty(formBean.getType())) {
            //参数类型
            criteria.andLike("type", "%" + formBean.getType() + "%");
        }
        example.orderBy("code");//参数编码：升序

        //分页查询
        PageHelper.startPage(pageNum, length);
        List<SCodeName> tableList = super.getByExample(example);
        formBean.setPageInfo(tableList);
        return formBean;
    }

    /**
     * 新增权限保存
     *
     * @return
     */
    @Override
    public int save(SCodeName sBean) {
        int retCnt = 0;
        String loginUserGuid = (String) SecurityUtils.getSubject().getSession().getAttribute("userSessionId");
        sBean.setUpdateUserGuid(loginUserGuid);
        sBean.setCreatedUserGuid(loginUserGuid);
        sBean.setGuid(getGuid());//guid
        retCnt = super.save(sBean);

        return retCnt;
    }

    /**
     * 修改权限保存
     *
     * @return
     */
    @Override
    public int update(SCodeName sBean) {
        String loginUserGuid = (String) SecurityUtils.getSubject().getSession().getAttribute("userSessionId");
        sBean.setUpdateUserGuid(loginUserGuid);
        int retCnt = super.update(sBean);

        return retCnt;
    }

    /**
     * 根据参数类型，获取参数选择列表
     *
     * @param codeNameType
     * @return
     */
    @Override
    public List<SCodeName> getCodeNameListByType(String codeNameType) {
        logger.info("根据参数类型，获取参数选择列表--开始");
        // 从缓存中获取城市信息
        String key = "codeNameType_" + codeNameType;
        ValueOperations<String, List<SCodeName>> operations = redisTemplate.opsForValue();

        // 缓存存在
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            List<SCodeName> sCodeNameList = operations.get(key);

            logger.info("getCodeNameListByType : 从缓存中获取了 >> " + sCodeNameList.toString());
            return sCodeNameList;
        }

        //分页查询
        Example example = new Example(SCodeName.class);
        Example.Criteria criteria = example.createCriteria();
        //参数类型
        criteria.andEqualTo("type", codeNameType);
        example.orderBy("code");//参数编码升序
        List<SCodeName> retList = super.getByExample(example);
        //参数基本类型情况
        if (codeNameType.equals(FinalUtil.CODE_NAME_ROOT_TYPE)) {
            SCodeName sCodeName = new SCodeName();
            sCodeName.setCode(FinalUtil.CODE_NAME_ROOT_TYPE);
            sCodeName.setName(FinalUtil.CODE_NAME_NAME);
            retList.add(0, sCodeName);
        }
        //--请选择--
        SCodeName sCodeName = new SCodeName();
        sCodeName.setCode(FinalUtil.CODE_NAME_TYPE_NULL);
        sCodeName.setName(FinalUtil.CODE_NAME_NAME_NULL);
        retList.add(0, sCodeName);
        logger.info("根据参数类型，获取参数选择列表--结束");
        // 插入缓存
        operations.set(key, retList, 10, TimeUnit.SECONDS);
        logger.info("getCodeNameListByType : 插入缓存 >> " + retList.toString());

        return retList;
    }

    /**
     * 根据参数类型，获取参数选择列表
     *
     * @param codeNameType
     * @return
     */
    @Override
    public List<SCodeName> getBWListByType(String codeNameType) {
        logger.info("根据参数类型，获取参数选择列表--开始");
        // 从缓存中获取信息
        String key = "codeNameType_" + codeNameType;
        ValueOperations<String, List<SCodeName>> operations = redisTemplate.opsForValue();

        // 缓存存在
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            List<SCodeName> sCodeNameList = operations.get(key);

            logger.info("getCodeNameListByType : 从缓存中获取了 >> " + sCodeNameList.toString());
            return sCodeNameList;
        }
        Map<String,String> pMap = new HashMap<String,String>();
        pMap.put("type", codeNameType);
        List<SCodeName> retList = sCodeNameMapper.selectBWListByType(pMap);
        logger.info("根据参数类型，获取参数选择列表--结束");
        // 插入缓存
        operations.set(key, retList, 10, TimeUnit.SECONDS);
        logger.info("getCodeNameListByType : 插入缓存 >> " + retList.toString());

        return retList;
    }

    @Override
    public String getNameByCode(String businessType) {
        return sCodeNameMapper.getNameByCode(businessType);
    }

    /**
     * 根据日期，取得当天开票流水号
     *
     * @return
     */
    @Override
    public String getInvoiceSellerNumber() {
        logger.info("开票流水号取得--开始");
        //shimao_
        StringBuffer strRtn = new StringBuffer(FinalUtil.INVLID_SELLER_SHIMAO + FinalUtil.PERMISSION_MENU_DOW);
        String strNumber = "1";
        Integer intNumber = 1;
        //当前日期
        String strDate = new SimpleDateFormat(MyDateUtil.format_yyyyMMdd).format(new Date());
        SCodeName sCodeName = new SCodeName();

        //查询
        Example example = new Example(SCodeName.class);
        Example.Criteria criteria = example.createCriteria();
        //参数类型invoice_no
        criteria.andEqualTo("type", FinalUtil.CODE_NAME_INVOICE_NO);
        //shimao_YYYYMMDD_
        strRtn.append(strDate + FinalUtil.PERMISSION_MENU_DOW);
        criteria.andEqualTo("code", strDate);
        List<SCodeName> retList = super.getByExample(example);
        if (retList.size() > 0) {
            sCodeName = retList.get(0);
            strNumber = sCodeName.getName();
            intNumber = Integer.parseInt(strNumber) + 1;//最大流水数字
            strNumber = intNumber + "";
        } else {
            //查询数据库中已存在的一条记录，然后更新
            // 数据库必须事先维护一条基础数据
            sCodeName.setType(FinalUtil.CODE_NAME_INVOICE_NO);
            sCodeName.setUpdateUserGuid(FinalUtil.INTER_FACE_USER_ID);
        }
        sCodeName.setCode(strDate);
        sCodeName.setName(strNumber);
        //根据type类型为invoice_no的去做更新
        sCodeNameMapper.updateByType(sCodeName);

        //shimao_YYYYMMDD_123456789123456789
        strRtn.append(StringUtils.left(FinalUtil.INVLID_SELLER_ZIRO, FinalUtil.INVLID_SELLER_LENGTH - StringUtils.length(strNumber)) + strNumber);
        logger.info("开票流水号取得--结束");
        return strRtn.toString();
    }

    /**
     * 取得自定义商品最大编号
     *
     * @return
     */
    @Override
    public String getMaxGoodsCode() {
        logger.info("自定义商品最大编号取得--开始");
        String strNumber = "1";
        Integer intNumber = 1;

        SCodeName sCodeName = new SCodeName();

        //查询
        Example example = new Example(SCodeName.class);
        Example.Criteria criteria = example.createCriteria();
        //参数类型goods_code
        criteria.andEqualTo("type", FinalUtil.CODE_NAME_GOODS_CODE);

        List<SCodeName> retList = super.getByExample(example);
        if (retList.size() > 0) {
            sCodeName = retList.get(0);
            strNumber = sCodeName.getCode();
            intNumber = Integer.parseInt(strNumber) + 1;//最大流水数字
            strNumber = intNumber + "";
        } else {
            //查询数据库中已存在的一条记录，然后更新
            // 数据库必须事先维护一条基础数据
            sCodeName.setType(FinalUtil.CODE_NAME_GOODS_CODE);
            sCodeName.setUpdateUserGuid(FinalUtil.INTER_FACE_USER_ID);
        }
        sCodeName.setCode(intNumber+"");
        //根据type类型为invoice_no的去做更新
        sCodeNameMapper.updateByType(sCodeName);

        while (strNumber.length()<10){
            strNumber="0"+strNumber;
        }
        logger.info("自定义商品最大编号取得--结束");
        return strNumber;
    }

}
